/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI.GerenciarTREF;

import Biblioteca.Library;
import Biblioteca.VerificacaoErros;
import ClassesUnicas.Profissional;
import DAO.DAOProfissional;
import DAO.MySQL.DAOProfissionalMySQL;
import GUI.LoginDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

/**
 * FrameDefault
 *
 * Versao 1.0
 *
 * Data 16/02/2013
 *
 * @author Igor
 */
public class FrameCRUDProfissional extends FramePattern implements InterfaceFrame {

    //Atributos
    private Profissional profissional;
    private DAOProfissional profissionalDAO;

    /**
     * Creates new form FrameDefault
     */
    public FrameCRUDProfissional() {
        initComponents();

        this.profissionalDAO = new DAOProfissionalMySQL();

        Library.reagirEnter(buttonLocalizar);
        Library.reagirEnter(buttonSalvar);
        Library.reagirEnter(buttonLimpar);

        Library.semCaracterEspecial(textNome);
        Library.semCaracterEspecial(textEmail);
        Library.semBarraDeEspaco(textEmail);
        Library.semCaracterEspecial(textSenha);

        this.addInternalFrameListener(
                new InternalFrameAdapter() {
                    @Override
                    public void internalFrameClosing(InternalFrameEvent e) {
                        //A operacao esta sendo realizada na classe FramePattern, nao eh necessario realizar nos InternalFrames
                        validarSair = !verificaCamposVaziosSair();
                    }
                }
        );
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelTitulo = new javax.swing.JPanel();
        labelTitulo = new javax.swing.JLabel();
        labelCamposObrigatorios = new javax.swing.JLabel();
        panelDadosPrincipais = new javax.swing.JPanel();
        labelNome = new javax.swing.JLabel();
        textNome = new javax.swing.JTextField();
        panelAcesso = new javax.swing.JPanel();
        labelEmail = new javax.swing.JLabel();
        textEmail = new javax.swing.JTextField();
        labelSenha = new javax.swing.JLabel();
        textSenha = new javax.swing.JPasswordField();
        labelConfirmarSenha = new javax.swing.JLabel();
        textConfirmarSenha = new javax.swing.JPasswordField();
        panelBotoes = new javax.swing.JPanel();
        buttonSalvar = new javax.swing.JButton();
        buttonLimpar = new javax.swing.JButton();
        buttonLocalizar = new javax.swing.JButton();
        buttonFechar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastro de Profissionais");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        panelTitulo.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        labelTitulo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        labelTitulo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelTitulo.setText("Tela utilizada para cadastrar e/ou alterar dados de um Profissional");

        labelCamposObrigatorios.setText("Campos marcados com * são obrigatórios");

        javax.swing.GroupLayout panelTituloLayout = new javax.swing.GroupLayout(panelTitulo);
        panelTitulo.setLayout(panelTituloLayout);
        panelTituloLayout.setHorizontalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelTitulo)
                    .addComponent(labelCamposObrigatorios))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        panelTituloLayout.setVerticalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(labelTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelCamposObrigatorios))
        );

        panelDadosPrincipais.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Dados Principais   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        labelNome.setText("*Nome:");

        panelAcesso.setBorder(javax.swing.BorderFactory.createTitledBorder("   Acesso   "));

        labelEmail.setText("E-mail:");

        labelSenha.setText("Senha:");

        labelConfirmarSenha.setText("Confirmar Senha:");

        javax.swing.GroupLayout panelAcessoLayout = new javax.swing.GroupLayout(panelAcesso);
        panelAcesso.setLayout(panelAcessoLayout);
        panelAcessoLayout.setHorizontalGroup(
            panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelAcessoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelEmail)
                    .addComponent(labelSenha)
                    .addComponent(labelConfirmarSenha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelAcessoLayout.setVerticalGroup(
            panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelAcessoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEmail)
                    .addComponent(textEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelSenha)
                    .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelAcessoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelConfirmarSenha)
                    .addComponent(textConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout panelDadosPrincipaisLayout = new javax.swing.GroupLayout(panelDadosPrincipais);
        panelDadosPrincipais.setLayout(panelDadosPrincipaisLayout);
        panelDadosPrincipaisLayout.setHorizontalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelNome)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(textNome)
                .addContainerGap())
            .addComponent(panelAcesso, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        panelDadosPrincipaisLayout.setVerticalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelNome)
                    .addComponent(textNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(panelAcesso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        panelBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        buttonSalvar.setText("Salvar");
        buttonSalvar.setToolTipText("Clique para salvar os dados digitados");
        buttonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSalvarActionPerformed(evt);
            }
        });

        buttonLimpar.setText("Limpar");
        buttonLimpar.setToolTipText("Clique para limpar a tela e habilitar um novo registro");
        buttonLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLimparActionPerformed(evt);
            }
        });

        buttonLocalizar.setText("Localizar");
        buttonLocalizar.setToolTipText("Clique para localizar um profissional e editar seus dados");
        buttonLocalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLocalizarActionPerformed(evt);
            }
        });

        buttonFechar.setText("Fechar");
        buttonFechar.setToolTipText("Cancela a operação e fecha a janela");
        buttonFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonFecharActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelBotoesLayout = new javax.swing.GroupLayout(panelBotoes);
        panelBotoes.setLayout(panelBotoesLayout);
        panelBotoesLayout.setHorizontalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotoesLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonLocalizar, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        panelBotoesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonFechar, buttonLimpar, buttonLocalizar, buttonSalvar});

        panelBotoesLayout.setVerticalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonLimpar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonLocalizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonFechar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelTitulo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelBotoes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        limparCampos();
    }//GEN-LAST:event_formComponentShown

    private void buttonLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLimparActionPerformed
        // TODO add your handling code here:
        this.profissional = null;
        limparCampos();
    }//GEN-LAST:event_buttonLimparActionPerformed

    private void buttonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSalvarActionPerformed
        // TODO add your handling code here:
        String mensagem = "";
        Boolean tudoCerto = true;

        try {
            if (textNome.getText().isEmpty() && tudoCerto) {
                tudoCerto = false;
                JOptionPane.showMessageDialog(null, "Digite um Nome para o profissional!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                textNome.grabFocus();
            }

            if (((textEmail.getText().isEmpty() && !textSenha.getText().isEmpty())
                    || (!textEmail.getText().isEmpty() && textSenha.getText().isEmpty()))
                    && tudoCerto) {
                tudoCerto = false;
                JOptionPane.showMessageDialog(null, "Se o profissional realmente terá acesso ao software\nsertifique-se de digitar E-mail e Senha!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                textEmail.grabFocus();
            }

            if (!textSenha.getText().equals(textConfirmarSenha.getText())) {
                tudoCerto = false;
                JOptionPane.showMessageDialog(null, "Os campos Senha e Confirmar Senha, não conferem!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
            }

            if (tudoCerto) {
                if (this.profissional == null) {
                    this.profissional = new Profissional();
                    this.profissional.setIdProfissional(-1);
                }

                this.profissional.setNome(textNome.getText());
                this.profissional.setEmail(textEmail.getText());
                this.profissional.setSenha(textSenha.getText());
                mensagem = this.profissionalDAO.gravaProfissional(this.profissional);

                if (mensagem.equals("SUCESSO")) {
                    this.profissional = null;
                    limparCampos();
                    JOptionPane.showMessageDialog(null, "Profissional cadastrado com sucesso!", "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, mensagem, "Atenção!", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, VerificacaoErros.retornaMensagemErro(e), "Erro!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonSalvarActionPerformed

    private void buttonLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLocalizarActionPerformed
        // TODO add your handling code here:
        Profissional prof = new Profissional();
        prof.setIdProfissional(-1);
        JDialog dlg = new JDialog();
        FrameLocalizaProfissional frame = new FrameLocalizaProfissional(prof, dlg);
        Library.criaInternalFrameDentroDialog(dlg, frame);
        if (prof.getIdProfissional() != -1) {
            this.profissional = this.profissionalDAO.buscaProfissional(String.valueOf(prof.getIdProfissional()));
            mostraDadosObjeto();
        }
    }//GEN-LAST:event_buttonLocalizarActionPerformed

    private void buttonFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonFecharActionPerformed
        // TODO add your handling code here:
        super.validarSair = !verificaCamposVaziosSair();
        super.fecharAplicacao();

    }//GEN-LAST:event_buttonFecharActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonFechar;
    private javax.swing.JButton buttonLimpar;
    private javax.swing.JButton buttonLocalizar;
    private javax.swing.JButton buttonSalvar;
    private javax.swing.JLabel labelCamposObrigatorios;
    private javax.swing.JLabel labelConfirmarSenha;
    private javax.swing.JLabel labelEmail;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelSenha;
    private javax.swing.JLabel labelTitulo;
    private javax.swing.JPanel panelAcesso;
    private javax.swing.JPanel panelBotoes;
    private javax.swing.JPanel panelDadosPrincipais;
    private javax.swing.JPanel panelTitulo;
    private javax.swing.JPasswordField textConfirmarSenha;
    private javax.swing.JTextField textEmail;
    private javax.swing.JTextField textNome;
    private javax.swing.JPasswordField textSenha;
    // End of variables declaration//GEN-END:variables

    @Override
    public void limparCampos() {
        Library.limpaTextos(panelDadosPrincipais);
        Library.limpaTextos(panelAcesso);
        textNome.grabFocus();
    }

    @Override
    public void mostraDadosObjeto() {
        textNome.setText(this.profissional.getNome());
        textEmail.setText(this.profissional.getEmail());
        textSenha.setText(this.profissional.getSenha());
        textConfirmarSenha.setText(this.profissional.getSenha());
    }

    /**
     * Verifica se todos campos estao vazio True todos campos estao vazio False
     * se existir campos nao vazios
     *
     * @return
     */
    private boolean verificaCamposVaziosSair() {
        if (!textNome.getText().isEmpty()
                || !textEmail.getText().isEmpty()
                || !textSenha.getText().isEmpty()
                || !textConfirmarSenha.getText().isEmpty()) {
            return false;
        }

        return true;
    }
}
